package game.menu;


import java.awt.Graphics2D;
import java.util.ArrayList;

public class MenuContainer {

	public static final int ELEMENT_SPACE = 30;

	private ArrayList<MenuElement> menuElements;

	double xPos;
	double yPos;

	private int selectedIndex = -1;

	public MenuContainer(double startXpos, double startY) {
		this(startXpos, startY, new ArrayList<MenuElement>());
	}

	public MenuContainer(double xPos, double startY, ArrayList<MenuElement> menuElements) {
		if (menuElements == null) {
			throw new RuntimeException("Null menuElements.");
		}
		this.menuElements = menuElements;
		this.xPos = xPos;
		this.yPos = startY;
		if (menuElements.size() > 0) {
			setSelected(0);
		}
	}

	public void addMenuElement(MenuElement element) {
		this.menuElements.add(element);
		yPos += ELEMENT_SPACE + MenuElement.BACKGROUND_HEIGHT;
		if (getSelectedIndex() < 0) {
			setSelected(0);
		}
	}

	public void addMenuElement(String key) {
		addMenuElement(new MenuElement(xPos, yPos, key));
	}

	public void addMenuElementWithOptions(String key) {
		addMenuElement(new MenuElementWithOptions(xPos, yPos, key));
	}

	public void cursorDown() {
		if (selectedIndex < menuElements.size() - 1) {
			setSelected(selectedIndex + 1);
		}
	}

	public void cursorUp() {
		if (selectedIndex > 0) {
			setSelected(selectedIndex - 1);
		}
	}

	public void drawMenu(Graphics2D g2d) {
		for (MenuElement element : menuElements) {
			element.drawElement(g2d);
		}
	}

	public MenuElement getElementAt(int index) {
		return menuElements.get(index);
	}

	public int getIndexForKey(String key) {
		if (key == null) {
			return -1;
		}
		for (int i = 0; i < menuElements.size(); i++) {
			if (key.equals(menuElements.get(i).getKey())) {
				return i;
			}
		}
		return -1;
	}

	public String getKeyForIndex(int index) {
		MenuElement element = getElementAt(index);
		if (element != null) {
			return element.getKey();
		} else
			return null;
	}

	public MenuElement getSelectedElement() {
		return getElementAt(selectedIndex);
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public String getSelectedKey() {
		return getKeyForIndex(selectedIndex);
	}

	public void setSelected(int newSelectedIndex) {
		if (selectedIndex != -1) {
			menuElements.get(selectedIndex).setSelected(false);
		}
		menuElements.get(newSelectedIndex).setSelected(true);
		selectedIndex = newSelectedIndex;
	}

}